package com.zxmc.server.service.impl;

import com.alibaba.fastjson2.JSON;
import com.zxmc.common.context.BaseContext;
import com.zxmc.pojo.dto.NovelQueryDto;
import com.zxmc.pojo.entity.BookShelf;
import com.zxmc.pojo.entity.Novel;
import com.zxmc.pojo.entity.ReadingHistory;
import com.zxmc.pojo.entity.User;
import com.zxmc.pojo.vo.ReadingHistoryVO;
import com.zxmc.server.mapper.ReadingHistoryMapper;
import com.zxmc.server.service.BookShelfService;
import com.zxmc.server.service.NovelService;
import com.zxmc.server.service.ReadingHistoryService;
import com.zxmc.server.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ReadingHistoryServiceImpl implements ReadingHistoryService {

    @Autowired
    private ReadingHistoryMapper readingHistoryMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private BookShelfService bookShelfService;
    @Autowired
    private UserService userService;
    @Autowired
    private NovelService novelService;

    @Override
    public ReadingHistory list(Integer novelId) {
        Integer userId= BaseContext.getCurrentId();
        String key="novelHistory:"+userId+":"+novelId;
        Object object = redisTemplate.opsForValue().get(key);
        if (object==null)
            return null;
        return JSON.to(ReadingHistory.class, object);
    }


    @Override
    public void insert(String key,ReadingHistory readingHistory) {
        LocalDateTime lastReadTime = null;
        // 检查是否已经存在相同的键
        if (redisTemplate.hasKey(key)) {
            // 如果存在，则更新该记录
            Object value = redisTemplate.opsForValue().get(key);
            lastReadTime = (Objects.requireNonNull(JSON.to(ReadingHistory.class, value))).getLastReadTime();
        }
        // 计算阅读时间
        Duration readTime = null;
        if (lastReadTime != null) {
            readTime = Duration.between(lastReadTime, LocalDateTime.now());
            readingHistory.setReadTime(readTime.getNano());
        }else {
            readingHistory.setReadTime(0);
        }
        // 保存记录
        redisTemplate.opsForValue().set(key, readingHistory,180, TimeUnit.DAYS); // 设置过期时间为180天
//        readingHistoryMapper.insert(readingHistory);
        //更新bookShelf
        //判断是否存在书架
        List<BookShelf> list = bookShelfService.list(readingHistory.getNovelId());
        if (list.isEmpty())
            return;
        BookShelf bookShelf = list.get(0);
        bookShelfService.update(readingHistory);
    }

    @Override
    public void update(ReadingHistory readingHistory) {

        readingHistoryMapper.update(readingHistory);
    }

    @Override
    public List<ReadingHistoryVO> listAll(Integer userId) {
        String key0="novelHistory:"+userId+":*";
        Set<String> keys = redisTemplate.keys(key0);
        if (keys.isEmpty())
            return Collections.emptyList();
        User user = userService.listById(userId);
        List<ReadingHistoryVO> readingHistoriesVOs = new ArrayList<>();
        for (String key : keys) {
            Object object = redisTemplate.opsForValue().get(key);
            ReadingHistory readingHistory = JSON.to(ReadingHistory.class, object);
            ReadingHistoryVO readingHistoryVO = new ReadingHistoryVO();
            if (readingHistory != null) {
                BeanUtils.copyProperties(readingHistory, readingHistoryVO);
                Integer novelId = readingHistory.getNovelId();
                Novel novel = novelService.list(NovelQueryDto.builder().id(novelId).build()).get(0);
                readingHistoryVO.setNovelName(novel.getTitle());
                readingHistoryVO.setUserName(user.getUsername());
                readingHistoryVO.setAvatar(user.getAvatar());

            }
            readingHistoriesVOs.add(readingHistoryVO);
        }
        // 按照 lastReadTime 倒序排序
        readingHistoriesVOs.sort((vo1, vo2) -> {
            if (vo1.getLastReadTime() == null && vo2.getLastReadTime() == null) {
                return 0;
            }
            if (vo1.getLastReadTime() == null) {
                return 1;
            }
            if (vo2.getLastReadTime() == null) {
                return -1;
            }
            return vo2.getLastReadTime().compareTo(vo1.getLastReadTime());
        });
        return readingHistoriesVOs;
    }

    @Override
    public void delete(User user) {
        String keyPattern = "novelHistory:" + user.getId()+":*";
        // 获取所有匹配的键
        Set<String> keys = redisTemplate.keys(keyPattern);
        if (!keys.isEmpty()) {
            // 删除所有匹配的键
            redisTemplate.delete(keys);
        }
    }

    @Override
    public void deleteByNovel(Novel novel) {
        String keyPattern = "novelHistory:*" +":"+novel.getId();
        // 获取所有匹配的键
        Set<String> keys = redisTemplate.keys(keyPattern);
        if (!keys.isEmpty()) {
            // 删除所有匹配的键
            redisTemplate.delete(keys);
        }
    }
}
